Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

251
Vistas
How to create a new constructor with each element from my Json file. [Javascript]

Basically this is my Json File:

[ 
  {
    "id": 9,
    "nombre": "ProductoDeJson4",
    "precio": 15000,
    "stock": 0,
    "img": ""
  },
  {
    "id": 10,
    "nombre": "ProductoDeJson5",
    "precio": 15000,
    "stock": 0,
    "img": ""
  }
]

This is my class:

class Producto {
  constructor(id, nombre, precio, stock) {
    this.id = id;
    this.nombre = nombre;
    this.precio = precio;
    this.stock = stock;
  }

  sumaIVA() {
    this.precio *= 1.21;
  }
  aumentarPrecio() {
    if (aumentoPrecios < 1) {
      this.precio = this.precio * aumentoPrecios + this.precio;
    } else {
      this.precio *= aumentoPrecios;
    }
  }
}

And i want to do this dynamically with the data from my Json. Because i want to apply the function "aumentarPrecio()" to each one.

const producto1 = new Producto(1, "Grasa", 400, 1);
const producto2 = new Producto(2, "Desengrasante", 1000, 1);

const productos = [
  producto1,
  producto2, 
];

Right now i'm trying to do it like this but itsn't working. The new Producto is being created but the functions from the class aren't working. I think it's because i'm not creating a new const for each element from the Json. But i don't know how to do it dynamically.

async function obtenerProductos() {
  const response = await fetch("productos.json");
  return await response.json();
}

let arrayProductos = obtenerProductos();
//Agrego productos del JSON al array de productos (falta agregarle los métodos o transformar cada uno en un new Producto)
arrayProductos.then((el) => {
  console.log(el);
  el.forEach((el) => {
    console.log(el["nombre"]);
    const productosJson = new Producto(
      el["id"],
      el["nombre"],
      el["precio"],
      el["stock"]
    );
    productos.push(productosJson);
    console.log("elemento pusheado");
  });
});
//Método Aumentar precio productos, luego de tener los productos listos en el array
productos.forEach((listaProductos) => {
  setTimeout(() => {
    listaProductos.aumentarPrecio();
    console.log("precios aumentados");
  }, 1000);
});

Please help me, haha. Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You're trying to dynamically create objects within a loop as far as i can tell.

This link might be what you are looking for.

Tldr:

  1. Create an empty list which will save the newly created objects
  2. Loop through your json as you do now but with a counter i and extract the data for current object
  3. Append each object to your list e.g objects[i] = new Producto(1, "Grasa", 400, 1); (watchout here, as you are not giving your objects any name, they will be called by object[i].function)
  4. call your function after or during you added the objects via object[i].aumentarPrecio()

On another note: You probably shouldnt declare the objects as const in your code and as it might clash with your out-of-class declaration of aumentoPrecios.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda